//
//  BIZConsultViewController.m
//  jiedabao
//
//  Created by 小龙 on 2017/3/15.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZConsultViewController.h"
#import "BIZRapidConsultCell.h"
#import "BIZConsultEditViewController.h"
#import "BIZConsultQModel.h"
#import "BIZRapidConsultResultVC.h"
#import "BIZQuestionModel.h"
static NSString *const RapidConsultCellID = @"BIZRapidConsultCellID";

@interface BIZConsultViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, assign) int last;
@property (nonatomic, copy) NSMutableArray *list;

@end

@implementation BIZConsultViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
    [self loadNew];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadRepaidHistoryListRedBadge) name:kReloadRepaidListRedBadgeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadNew) name:kReloadRepaidListNotification object:nil];
}

- (void)reloadRepaidHistoryListRedBadge
{
    NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
    BIZQuestionModel *model = self.list[indexPath.section];
    model.status = @"1";
    if (indexPath) {
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
    
}



-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self getTabBarRedBadgeData];
}


- (void)getTabBarRedBadgeData
{
    if (![BIZUserModel shareUser].login) {
        return;
    }
    
    [RequestTool POST:kTabBarRedBadgeUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"kTabBarRedStatusURL---responseObject %@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            if (([responseObject[@"data"][@"oneRed"] integerValue])
                ||([responseObject[@"data"][@"rapidRed"]  integerValue])) {
                [self.tabBarController.tabBar.items[0] showBadge];
            } else {
                [self.tabBarController.tabBar.items[0] hidenBadge];
            }
        
        }
        else {
            [MBProgressHUD showInfoMessage:responseObject[@"des"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}



- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.automaticallyAdjustsScrollViewInsets = YES;
}

- (void)rightBarButtonItemClick
{
    MJWeakSelf;
    BIZConsultEditViewController *bizEdit = [[BIZConsultEditViewController alloc] initWithType:BIZConsultEditTypeRapid cuserId:nil finishBlock:^(BIZConsultQModel *model) {
        
        [weakSelf loadNew];
        
        BIZRapidConsultResultVC *vc = [[BIZRapidConsultResultVC alloc] init];
        vc.alertTitleStr = @"您的问题已提交，请耐心等待咨询师回复";
        vc.questionModel =(BIZQuestionModel*)model;
//        vc.questionModel.name = [BIZUserModel shareUser].name;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    BIZNavigationController *nav = [[BIZNavigationController alloc] initWithRootViewController:bizEdit];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)setupTableView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.estimatedRowHeight = 200;
    self.tableView.tableHeaderView.height = 70;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadConsult)];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BIZRapidConsultCell class]) bundle:nil] forCellReuseIdentifier:RapidConsultCellID];

}


- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}

#pragma mark - 接口

- (void)loadNew
{
    self.last = 1;
    [self.list removeAllObjects];
    [self loadConsult];
}



- (void)loadConsult
{
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kRapidListUrl
           parameters:@{@"pageIndex" : @(_last), @"pageEnd" : @(_last + 9)}
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  
                  NSLog(@"response %@", responseObject);
                  [MBProgressHUD hideHUD];
                  [self stopRefresh];
                  
                  BIZQuestionModelListModel *model = [BIZQuestionModelListModel yy_modelWithJSON:responseObject];
                  
                  if (model.code == 1) {
                      [self.list addObjectsFromArray:model.questionArr];
                       _last += model.questionArr.count;
                      [self.tableView reloadData];
                  }
                  else if (model.code == 2){
                      [MBProgressHUD showInfoMessage:model.des];
                      
                      BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                      MPWeakSelf(self);
                      vc.loginSuccessBlock = ^(){
                          [weakself loadNew];
                      };
                      [self presentViewController:vc animated:YES completion:nil];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:model.des];
                  }
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  [self stopRefresh];
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
              }
     ];
}


#pragma mark - tableView


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.list.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BIZRapidConsultCell *cell = [tableView dequeueReusableCellWithIdentifier:RapidConsultCellID forIndexPath:indexPath];
    
    cell.questionModel = self.list[indexPath.row];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BIZQuestionModel *model = self.list[indexPath.row];
    BIZRapidConsultResultVC *vc = [[BIZRapidConsultResultVC alloc]init];
    vc.alertTitleStr = nil;
    vc.questionModel = model;
    MPWeakSelf(self);
    vc.adoptBtnClickBlock = ^(){
        model.status = @"1";
        [weakself.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationFade];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)publicQustionBtnClick {
    [self rightBarButtonItemClick];
}

#pragma mark -
- (NSMutableArray *)list
{
    if (!_list) {
        _list = [NSMutableArray array];
    }
    return _list;
}


@end
